import { KitchensolutionService } from './../service/kitchensolutionService';
import { CloudSyncService } from './../service/cloudSyncService';
import { DeviceService } from './../service/deviceService';
import { Response, ServiceConfig, route, Guid } from '../common';
import { Device } from '../domain/model';
import { WebException } from './webException';
import assert = require("assert");
import * as Koa from "koa";

export class DeviceController {
    private deviceService: DeviceService;
    private syncSvr: CloudSyncService;
    private kitchensolutionService: KitchensolutionService;
    constructor() {
        this.deviceService = ServiceConfig.Current.GetService<DeviceService>("deviceService");
        this.syncSvr = ServiceConfig.Current.GetService<CloudSyncService>("cloudSyncService");
        this.kitchensolutionService = ServiceConfig.Current.GetService<KitchensolutionService>("kitchensolutionService");
    }

    toString() {
        return "DeviceController";
    }

    @route({ method: "post", path: "/api/devices" })
    async generateDevice(ctx: Koa.Context, next) {
        const storeId = ctx.accept.headers["storeid"];
        const terminal = ctx.request.body.terminal;
        const user = ctx.request.body.user;

        const result = await this.deviceService.generateDevice(ctx.request.body);
        ctx.response.body = Response.ok("success", result);

        this.syncSvr.DomainDataSyncPackage([
            {
                id: result.generatedDevice.id,
                body: result.generatedDevice,
                entityName: "devices"
            }
        ], {
                storeId,
                terminal,
                user
            });

        await next();
    }

    @route({ method: "put", path: "/api/devices/:id/" })
    async addDevice(ctx: Koa.Context, next) {
        const storeId = ctx.accept.headers["storeid"];
        const terminal = ctx.request.body.terminal;
        const user = ctx.request.body.user;

        if ((ctx.request.body && ctx.request.body.id) != ctx.params.id) {
            throw new WebException( "id不一致");
        }
        const bodyDevice = ctx.request.body;
        delete bodyDevice.user;
        delete bodyDevice.terminal
        const currentDevice = await this.deviceService.addDevice(bodyDevice);
        ctx.response.body = Response.ok("success", { currentDevice });

        this.syncSvr.DomainDataSyncPackage([
            {
                id: currentDevice.id,
                body: currentDevice,
                entityName: "devices"
            }
        ], {
                storeId,
                terminal,
                user
            });

        await next();
    }

    @route({ method: "get", path: "/api/devices/:id" })
    async getDevice(ctx: Koa.Context, next) {
        const id = ctx.params.id;
        const devices = await this.deviceService.queryDevices({ id })
        const kitchensolutions = await this.kitchensolutionService.getAllKitchensolutions();
        devices.forEach(v => {
            v.kitchenSolution = kitchensolutions.find(x => x.id == v.kitchenSolutionId)
        })
        ctx.response.body = Response.ok("查询成功", devices[0]);
        await next();
    }

    @route({ method: "get", path: "/api/devices" })
    async getDevices(ctx: Koa.Context, next) {
        const query = ctx.request.query;
        const queryWhite = ["deviceType"];
        for (let key in query) {
            if (queryWhite.indexOf(key) == -1) {
                throw new WebException( key + "参数不合法");
            }
        }
        let devices;
        if (Object.keys(query).length == 0) {
            devices = await this.deviceService.queryDevices()
        } else {
            devices = await this.deviceService.queryDevices(query)
        }
        const kitchensolutions = await this.kitchensolutionService.getAllKitchensolutions();
        devices.forEach(v => {
            v.kitchenSolution = kitchensolutions.find(x => x.id == v.kitchenSolutionId)
        })
        ctx.response.body = Response.ok("查询成功", devices);;
        await next();
    }

    @route({ method: "post", path: "/api/devices/:id/merge" })
    async mergeDevices(ctx: Koa.Context, next) {
        const storeId = ctx.accept.headers["storeid"];
        const terminal = ctx.request.body.terminal;
        const user = ctx.request.body.user;

        const id = ctx.params.id;
        const deviceIds = ctx.request.body.devices;
        if (!id) {
            throw new WebException( "缺少id")
        }
        const device = await this.deviceService.mergeDevices(id, deviceIds)
        ctx.response.body = Response.ok("合并成功", device);

        const syncDevices = await this.deviceService.queryDevices({ deviceType: "kds-printer" });
        syncDevices.forEach(v => {
            this.syncSvr.DomainDataSyncPackage([
                {
                    id: v.id,
                    body: v,
                    entityName: "devices"
                }
            ], {
                    storeId,
                    terminal,
                    user
                });

        })
        await next();
    }

    @route({ method: "post", path: "/api/devices/:id/unmerge" })
    async unmergeDevices(ctx: Koa.Context, next) {
        const storeId = ctx.accept.headers["storeid"];
        const terminal = ctx.request.body.terminal;
        const user = ctx.request.body.user;

        const id = ctx.params.id;
        const deviceIds = ctx.request.body.devices;
        if (!id) {
            throw new WebException( "缺少id")
        }
        const device = await this.deviceService.unmergeDevices(id, deviceIds)
        ctx.response.body = Response.ok("取消合并成功", device);

        const syncDevices = await this.deviceService.queryDevices({ deviceType: "kds-printer" });
        syncDevices.forEach(v => {
            this.syncSvr.DomainDataSyncPackage([
                {
                    id: v.id,
                    body: v,
                    entityName: "devices"
                }
            ], {
                    storeId,
                    terminal,
                    user
                })
        })

        await next();
    }

    @route({ method: "post", path: "/api/devices/:id/transfer" })
    async transferDevice(ctx: Koa.Context, next) {
        const storeId = ctx.accept.headers["storeid"];
        const terminal = ctx.request.body.terminal;
        const user = ctx.request.body.user;

        const id = ctx.params.id;
        const transferOutId = ctx.request.body.transferOutId;
        if (!id) {
            throw new WebException( "缺少id")
        }
        const result = await this.deviceService.transferDevice(id, transferOutId)
        ctx.response.body = Response.ok("转移", result.masterDevice);

        this.syncSvr.DomainDataSyncPackage(
            Object.keys(result).map(key => result[key]).map(x => {
                return {
                    id: x.id,
                    body: x,
                    entityName: "devices"
                }
            })
            , {
                storeId,
                terminal,
                user
            }
        );


        await next();
    }

    @route({ method: "post", path: "/api/devices/:id/changeKitchenSolutionId" })
    async changeDeviceKitchenSolution(ctx: Koa.Context, next) {
        const storeId = ctx.accept.headers["storeid"];
        const terminal = ctx.request.body.terminal;
        const user = ctx.request.body.user;

        const id = ctx.params.id;
        const KitchenSolutionId = ctx.request.body.KitchenSolutionId;
        if (!id) {
            throw new WebException( "缺少id")
        }
        const result = await this.deviceService.changeDeviceKitchenSolution(id, KitchenSolutionId)
        ctx.response.body = Response.ok("转移", result.device);

        this.syncSvr.DomainDataSyncPackage(
            Object.keys(result).map(key => result[key]).map(x => {
                return {
                    id: x.id,
                    body: x,
                    entityName: "devices"
                }
            })
            , {
                storeId,
                terminal,
                user
            }
        );
        await next();
    }

    @route({ method: "post", path: "/api/devices/:id/cancelTransfer" })
    async cancelTransferDevice(ctx: Koa.Context, next) {
        const storeId = ctx.accept.headers["storeid"];
        const terminal = ctx.request.body.terminal;
        const user = ctx.request.body.user;

        const id = ctx.params.id;
        const transferOutId = ctx.request.body.transferOutId;
        if (!id) {
            throw new WebException( "缺少id")
        }
        const result = await this.deviceService.cancelTransferDevice(id, transferOutId)
        ctx.response.body = Response.ok("取消转移成功", result.masterDevice);

        this.syncSvr.DomainDataSyncPackage(
            Object.keys(result).map(key => result[key]).map(x => {
                return {
                    id: x.id,
                    body: x,
                    entityName: "devices"
                }
            })
            , {
                storeId,
                terminal,
                user
            }
        );

        await next();
    }
}